﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Stock.Core
{
    public class ClientPoint
    {
        public string userid { get; set; }
        public EndPoint point { get; set; }
    }

    public class NetManager
    {
        public static List<ClientPoint> clients = new List<ClientPoint>();
        static Socket server;

        public NetManager()
        {
            
        }

        public static void Bind()
        {
			server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			server.Bind(new IPEndPoint(IPAddress.Any, 6001));//绑定端口号和IP
			//Console.WriteLine("服务端已经开启");
			Thread t = new Thread(ReciveMsg);//开启接收消息线程
			t.Start();
        }

		/// <summary>
		/// 接收发送给本机ip对应端口号的数据报
		/// </summary>
	 static void ReciveMsg()
		{
			while (true)
			{
				EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
				byte[] buffer = new byte[1024];
				int length = server.ReceiveFrom(buffer, ref point);//接收数据报
				string message = Encoding.UTF8.GetString(buffer, 0, length);
                if(message.Length > 0)
                {
                    var c = clients.Find(a => a.userid == message);
                    if (c != null)
                    {
                        try
                        {
                            var cc = c.point as IPEndPoint;
                            var p = point as IPEndPoint;
                            if(p.Address != cc.Address && p.Port != cc.Port)
                            {
                                sendMsgToClient(c.point, JsonConvert.SerializeObject(new { data = "exit" }));
                            }
						}
                        catch(Exception ex)
                        {
                            
                        }

                        c.point = point;
                    }
                    else
                        clients.Add(new ClientPoint() { userid = message, point = point });
                }

			}
		}

        public static void sendManagerMsg(string content)
        {
			Thread t = new Thread(() =>
			{

				byte[] b = Encoding.UTF8.GetBytes(content);

                var c = clients.Find(a=>a.userid == "72420c40-e1c9-430c-8257-08d4b70ca81a");
                if(c != null)
                {
                    server.SendTo(b, c.point);
                }

			});//开启接收消息线程
			t.Start();
        }

        public static void sendMsgToClient(EndPoint p, string content)
		{
			Thread t = new Thread(() =>
			{

				byte[] b = Encoding.UTF8.GetBytes(content);

				
				if (p != null)
				{
					server.SendTo(b, p);
				}

			});//开启接收消息线程
			t.Start();
		} 

		/// <summary>
		/// 向特定ip的主机的端口发送数据报
		/// </summary>
        public static void sendMsg(string content)
		{
            Thread t = new Thread(()=>{
                
				byte[] b = Encoding.UTF8.GetBytes(content);

				clients.ForEach(c =>
				{
					server.SendTo(b, c.point);
				});

            });//开启接收消息线程
			t.Start();


		}
    }
}
